package com.yuzhi.master.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuzhi.master.water.domain.DrainSewageMedicine;
import com.yuzhi.master.water.domain.vo.DrainSewageMedicineVo;
import com.yuzhi.master.water.mapper.DrainSewageMedicineMapper;
import com.yuzhi.master.water.service.IDrainSewageMedicineService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 污水厂维护费用信息Service业务层处理
 * @author auto code generator
 * @date 2024-04-12
 */
@RequiredArgsConstructor
@Service
public class DrainSewageMedicineServiceImpl implements IDrainSewageMedicineService {


    private final DrainSewageMedicineMapper drainSewageMedicineMapper;

    @Override
    public List<DrainSewageMedicine> selectListInfo()
    {

        List<DrainSewageMedicine>  list  =  drainSewageMedicineMapper.selectList();


        return  list;

    }

    /**
     * 首页运行账本
     * @param  queryDateType(1:近七日  2:按当前年月  3:按年份)
     * @return
     */
    @Override
    public Map<String, Object>  countSewageMedicine(String queryDateType)
    {
        List<DrainSewageMedicine>  list = new ArrayList<>();

        if("1".equals(queryDateType))   //近七日
        {
            LambdaQueryWrapper<DrainSewageMedicine> wrapper = new LambdaQueryWrapper<>();
            wrapper.ge(DrainSewageMedicine::getCjDate, LocalDateTime.now().minusDays(7))  // 7天前
                    .le(DrainSewageMedicine::getCjDate, LocalDateTime.now());            // 到现在

            list  =  drainSewageMedicineMapper.selectList(wrapper);
            if(!list.isEmpty())
            {
                //转换为年-月-日
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
                list.forEach(obj -> {
                    // CjDate(LocalDateTime)转换为String并赋值给CjDateStr
                    obj.setCjDateStr(obj.getCjDate().format(formatter));
                });
            }

        }
        else if("2".equals(queryDateType))//按月统计
        {
            // 查询当前月份及往前推12个月的时间段
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            //起始时间  算12个月前的起始时间（当月1日 00:00:00）
            LocalDateTime monthStart = now.minusMonths(11)  // 减11个月，因为包含当前月共12个月
                    .withDayOfMonth(1)
                    .withHour(0)
                    .withMinute(0)
                    .withSecond(0);
            // 计算当前月的结束时间（当月最后一天 23:59:59）
            LocalDateTime monthEnd = now.with(TemporalAdjusters.lastDayOfMonth())
                    .withHour(23)
                    .withMinute(59)
                    .withSecond(59);

            LambdaQueryWrapper<DrainSewageMedicine> wrapper = new LambdaQueryWrapper<>();
            wrapper.between(DrainSewageMedicine::getCjDate, monthStart, monthEnd);

            list  =  drainSewageMedicineMapper.selectList(wrapper);
            if(!list.isEmpty())
            {
                //转换为年-月格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
                list.forEach(obj -> {
                    // CjDate(LocalDateTime)转换为String并赋值给CjDateStr
                    obj.setCjDateStr(obj.getCjDate().format(formatter));
                });
            }
        }
        else
        {
            //按年份汇总
            list  =  drainSewageMedicineMapper.selectList();
            if(!list.isEmpty())
            {
                //转换为年
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
                list.forEach(obj -> {
                    // CjDate(LocalDateTime)转换为String并赋值给CjDateStr
                    obj.setCjDateStr(obj.getCjDate().format(formatter));
                });
            }
        }


        // 1. 按时间和类型分组统计求和summingDouble
        Map<String, Map<String, Double>> stats = list.stream()
                .filter(item -> item.getMedicine() != null)  // 先过滤掉 medicine 为 null 的记录
                .collect(Collectors.groupingBy(
                        DrainSewageMedicine::getCjDateStr,
                        TreeMap::new, // 保持时间顺序
                        Collectors.groupingBy(
                                DrainSewageMedicine::getFkType,
                                Collectors.summingDouble(DrainSewageMedicine::getMedicine)
                        )
                ));

        // 转换为万元单位
        stats.forEach((date, typeMap) ->
                typeMap.replaceAll((type, sum) ->
                        BigDecimal.valueOf(sum / 10000.0)
                                .setScale(2, RoundingMode.HALF_UP)
                                .doubleValue()
                )
        );

        //构建ECharts所需数据结构
        Map<String, Object> chartData = new LinkedHashMap<>();

        // X轴数据（采集时间，已排序）
        List<String> xAxisData = new ArrayList<>(stats.keySet());
        chartData.put("xAxisData", xAxisData);

        // 图例数据（采集类型）
        Set<String> legendData = stats.values().stream()
                .flatMap(map -> map.keySet().stream())
                .collect(Collectors.toCollection(LinkedHashSet::new)); // 保持顺序
        chartData.put("legendData", new ArrayList<>(legendData));

        Map<String,String>  codeMap  = new HashMap<>();
        codeMap.put("1","污水厂");
        codeMap.put("2","污水泵站");
        codeMap.put("3","维修表单");

        // 系列数据（每种类型的费用数据）
        List<Map<String, Object>> series = new ArrayList<>();
        legendData.forEach(type -> {
            Map<String, Object> seriesItem = new HashMap<>();
            seriesItem.put("name", codeMap.get(type));
            seriesItem.put("type", "bar");

            List<Double> data = xAxisData.stream()
                    .map(time -> stats.get(time).getOrDefault(type, 0.0))
                    .collect(Collectors.toList());

            seriesItem.put("data", data);
            series.add(seriesItem);
        });

        chartData.put("series", series);

        return chartData;
    }



    /**
     * 统计当天电量
     * @return
     */
    @Override
    public List<DrainSewageMedicineVo>   findBatPowByDay()
    {
        return drainSewageMedicineMapper.findBatPowByDay();
    }

}
